layui.use(['layer', 'form', 'table', 'admin', 'treetable', 'util'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var admin = layui.admin;
    var treetable = layui.treetable;
    var util = layui.util;
    var leadingOfficalPerson;
    var regionCatalogType;
    var Authorization;//请求接口用

    var setting = {//树设置
        identValueSetting: {//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub",
                    isParent: "isParent",
                    title: "name"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandIdentValueTree,
                onClick: identValueOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }
    //编辑树形菜单
    var editsetting = {//树设置
        identValueSetting: {//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub",
                    isParent: "isParent",
                    title: "name"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: editonExpandIdentValueTree,
                onClick: editidentValueOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }
    form.verify({
        contactNumber: [/^1[3|4|5|7|8]\d{9}$/, '手机必须11位，只能是数字！'],
        email: [/^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/, '邮箱格式不对'],
        fax: [/^$|^(\d{3,4}-)?\d{7,8}$/, '请输入正确的传真号'],
        website: [/^$|^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/, '请输入的网址格式不正确'],
        zipCode: [/^$|^[0-9]{6}$/, '请输入正确的邮编'],
    });
    //获取权限方法
    var userInfo = getAuthority();

    if (userInfo) {
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type + " " + access_token;
        getMenuTreeTable();
        getLeadingOffical();
        getRegionVersion();
    }

    // 添加按钮点击事件
    $('#btnAddAuth').click(function () {
        showAddResourceModel();
    });

    // 工具条点击事件
    table.on('tool(tableAuth)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'add') { // 新增
            showAddResourceModel(data);
        } else if (layEvent === 'edit') { // 修改
            showEditResourceModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(data);
        }
    });

    $('#btnRefreshAuth').click(function () {
        getMenuTreeTable();
    });

    //查询下方区划树的下级区划值（懒加载）
    function onExpandIdentValueTree(event, treeId, treeNode) {

        if (treeNode.sub.length > 0 || treeNode.hasChild == '0') {
            return false
        }
        getTreeTable(treeNode, function (resArr) {
            const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
            treeNode = treeObj.addNodes(treeNode, resArr);
        });
    }
    //选中分组值
    function identValueOnClick(event, treeId, treeNode) {
        menuDetails = treeNode
        parCode = treeNode.code
        par_id = treeNode.id
        IdentValueSelected = treeNode;
        $("#region_code_text").val(treeNode.code)
        $('.modle-version').css('display', 'none')
    }
    //编辑弹窗
    //查询下方区划树的下级区划值（懒加载）
    function editonExpandIdentValueTree(event, treeId, treeNode) {

        if (treeNode.sub.length > 0 || treeNode.hasChild == '0') {
            return false
        }
        getTreeTable(treeNode, function (resArr) {
            const treeObj = $.fn.zTree.getZTreeObj("edit_tree");
            treeNode = treeObj.addNodes(treeNode, resArr);
        });
    }
    //选中分组值
    function editidentValueOnClick(event, treeId, treeNode) {
        menuDetails = treeNode
        parCode = treeNode.code
        par_id = treeNode.id
        IdentValueSelected = treeNode;
        $("#edit_region_code_text").val(treeNode.code)
        $('.edit-modle-version').css('display', 'none')
    }
    //获取树形目录的值
    function getTreeTable(obj, callback) {
        var req = {
            rcId: obj.rcid ? obj.rcid : obj.value,
            regionCode: obj.code || "",
        };
        axios.get(regionUrl.info.queryRegion, {
            params: req,
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data;
                    var resArr = [];
                    zhuanHuanTree(data, resArr);
                    parCode = '';
                    par_id = '';
                    menuDetails = {};
                    // IdentValueTree = resArr;
                    callback(resArr)
                    callback(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //请求菜单树表格
    function getMenuTreeTable() {
        let req = {
            region_code: "510000000000"
        }
        axios.get(systemUrl.organization.organizationTree, {
            params: req,
            headers: {
                'Authorization': Authorization
            },
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data;
                    var resArr = [];
                    formatData(data, resArr)
                    renderTable(resArr);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //格式化数据
    function formatData(tdata, resArr) {
        if (Array.isArray(tdata) && tdata.length > 0) {
            tdata.forEach(function (value, i) {
                resArr.push(value);
                formatData(value.children, resArr);
            });
        }
    }
    //转换菜单集合数据
    function zhuanHuanTree(tdata, resData) {
        if (Array.isArray(tdata) && tdata.length > 0) {
            tdata.forEach(function (v, i) {
                var newValue = v.name;
                resData[i] = v;
                resData[i].title = newValue;
                resData[i].icon = "";
                resData[i].isParent = "true";
                resData[i].sub = [];
            });
        }
    }
    //渲染树表格
    function renderTable(treedata) {
        treetable.render({
            treeColIndex: 1,
            treeSpid: -1,
            treeIdName: 'id',
            treePidName: 'parentId',
            elem: '#tableAuth',
            page: false,
            data: treedata,
            treeDefaultClose: true,
            cols: [[
                { type: 'numbers', title: '#' },
                { field: 'fullName', title: '组织名称', minWidth: 200 },
                { field: 'regionCode', title: '区划代码', minWidth: 200 },
                {
                    title: '创建日期', minWidth: 200, templet: function (d) {
                        return util.toDateString(d.createTime);
                    }
                },
                { templet: '#tableBarAuth', title: '操作', align: 'center', minWidth: 120 }
            ]],
            done: function () {
                layer.closeAll('loading');
            }
        });
    }
    //获取负责人信息
    function getLeadingOffical() {
        var req = {
            current: 1,
            size: 10000,
        };
        axios.get(systemUrl.userList, {
            params: req,
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    var data = response.data.data.records;
                    leadingOfficalPerson = data
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    //获取区划版本
    function getRegionVersion() {
        var req = {
            current: 1,
            size: 100,
            flag: 0
        };
        axios.get(regionUrl.catalog.catalogList, {
            params: req,
            headers: {
                'Authorization': Authorization
            }
        })
            .then(function (response) {
                if (response.status == 200 && response.data.message == "success") {
                    regionCatalogType = response.data.data.records;
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }
    //新增菜单
    function showAddResourceModel(obj) {

        admin.open({
            type: 1,
            title: '新增组织',
            content: $('#AddResourceModel').html(),
            success: function (layero, dIndex) {
                let str = template("template-leadingOffical-tmpl", { leadingOfficalPerson });
                document.getElementById("leadingOffical").innerHTML = str;

                let new_str = template("template-version-tmpl", { regionCatalogType });
                document.getElementById("regionVersion").innerHTML = new_str;
                form.render('select');
                if (obj) {
                    $('#addParentId').css('display', 'block');
                    $('#region_code').css('display', 'none');
                    $('#region_version').css('display', 'none');
                    var req = {};
                    req.parentId = obj.fullName
                    req.regionCode = obj.regionCode
                    form.val('AddResourceForm', req);  // 回显数据
                }

                // 表单提交事件
                form.on('submit(modelSubmitAuth)', function (data) {
                    layer.load(2);
                    data.field.parentId = obj ? obj.id : -1;
                    let req_data = data.field;
                    console.log('req_data:',req_data)
                    axios({
                        method: 'post',
                        url: systemUrl.organization.addOrganization,
                        data: req_data,
                        headers: {
                            'Authorization': Authorization,
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200 && res.data.message == "success") {
                                getMenuTreeTable();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", { icon: 1 });
                            } else {
                                layer.msg(res.data.message, { icon: 2 });
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        })
                    return false;
                });

                form.on('select(regionVersion)', function (select_data) {
                    getTreeTable(select_data, function (resArr) {
                        $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                        $('.modle-version').css('display', 'block')
                        $('.modle-version').mouseleave(function () {
                            $('.modle-version').css('display', 'none')
                        })
                    });
                })


            }
        });
    }

    // 删除菜单
    function doDel(data) {
        layer.confirm('此操作将删除该资源，是否继续？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (index) {
            layer.close(index);
            layer.load(2);
            axios({
                method: 'DELETE',
                url: systemUrl.organization.deleteOrganization + data.id,
                headers: {
                    'Authorization': Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200 && res.data.message == "success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", { icon: 1 });
                        getMenuTreeTable();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, { icon: 2 });
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    //编辑菜单
    function showEditResourceModel(obj) {
        admin.open({
            type: 1,
            title: '编辑权限',
            content: $('#editResourceModel').html(),
            success: function (layero, dIndex) {
                let new_str = template("template-version-tmpl", { regionCatalogType });
                document.getElementById("edit_regionVersion").innerHTML = new_str;

                let str = template("template-leadingOffical-tmpl", { leadingOfficalPerson });
                document.getElementById("edit_leadingOffical").innerHTML = str;
                form.render('select');
                if (obj.parentId != -1) {
                    $('#addParentId').css('display', 'block')
                    $('#region_code_edit').css('display', 'none');
                    $('#region_version').css('display', 'none');
                }
                let edit_parentId = obj.parentId;
                obj.parentId = obj.fullName
                form.val('editResourceForm', obj);  // 回显数据


                form.on('select(edit_regionVersion)', function (select_data) {
                    getTreeTable(select_data, function (resArr) {
                        $.fn.zTree.init($("#edit_tree"), editsetting.identValueSetting, resArr);
                        $('.edit-modle-version').css('display', 'block')
                        $('.edit-modle-version').mouseleave(function () {
                            $('.edit-modle-version').css('display', 'none')
                        })
                    });
                })
                // 表单提交事件
                form.on('submit(modelSubmitAuth)', function (data) {
                    data.field.id = obj.id;
                    data.field.parentId = edit_parentId;
                    let edit_data = data.field;
                    layer.load(2);
                    axios({
                        method: 'put',
                        url: systemUrl.organization.editOrganization,
                        data: edit_data,
                        headers: {
                            'Authorization': Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200 && res.data.message == "success") {
                                getMenuTreeTable();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", { icon: 1 });
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, { icon: 2 });
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        })
                    return false;
                });

            }
        });
    }
});
